package upload

import (
	"fmt"
	"gin-blog/utils/logging"
	"gin-blog/utils/setting"
	"gin-blog/utils/helper"
	"log"
	"mime/multipart"
	"os"
	"path"
	"strconv"
	"strings"
)

// 获取图片完整链接
func GetImageFullUrl(name string) string {
	port := strconv.Itoa(setting.ServerSetting.HttpPort)
	return setting.AppSetting.ImagePrefixUrl + ":" + port + "/" + GetImagePath() + name
}

// 获取图片相对存放路径
func GetImagePath() string {
	return setting.AppSetting.ImageSavePath
}

// 获取hash后的图片名字
func GetImageName(name string) string {
	ext := path.Ext(name)
	filename := strings.TrimSuffix(name, ext)
	filename = helper.EncodeMD5(filename)

	return filename + ext
}

// 获取图片完整存放链接
func GetImageFullPath() string {
	return setting.AppSetting.RuntimeRootPath + GetImagePath()
}

// 检查上传文件类型是否合法
func CheckImageExt(filename string) bool {
	ext := path.Ext(filename)

	for _, allowExt := range setting.AppSetting.ImageAllowExts {
		if strings.ToUpper(allowExt) == strings.ToUpper(ext) {
			return true
		}
	}

	return false
}

// 检查上传文件大小是否超过限制
func CheckImageSize(f multipart.File) bool  {
	size, err := helper.GetSize(f)

	if err != nil {
		log.Println(err)
		logging.Warn(err)
		return false
	}

	return size <= setting.AppSetting.ImageMaxSize
}

func CheckImage(src string) error {
	dir, err := os.Getwd()

	if err != nil {
		return fmt.Errorf("os.Getwd err: %v", err)
	}

	err = helper.IsNotExistMKDir(dir + "/" + src)

	if err != nil {
		return fmt.Errorf("file.IsNotExistMkDir err: %v", err)
	}

	perm := helper.CheckPermission(src)

	if perm == true {
		return fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}
	return nil
}